package com.jenkins.test.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName: {@link JwtConfig}
 * @Description: JwtConfig
 * @author: Lanzhou
 * @date: 2020/10/3 16:50
 * @QQ: 1627518680
 * @Copyright:2020 All rights reserved.
 */
@Component
@ConfigurationProperties(prefix = "jwt.config")
public class JwtConfig {

    /**
     * 盐
     */
    private String secret;
    /**
     * token过期时间间隔(s)
     */
    private int expire;
    /**
     * 头部信息
     */
    private String header;


    /**
     * 创建Token, 不需要过期时间, 时间另外维护
     *
     * @param subject
     * @return
     */
    public String createToken(String key, String subject) {
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim(key, subject);
        return builder.sign(Algorithm.HMAC256(secret));
    }

    /**
     * 创建Token, 不需要过期时间, 时间另外维护
     *
     * @param subject
     * @return
     */
    public String createToken(String key, Date expire, String subject) {
        JWTCreator.Builder builder = JWT.create();
        builder.withExpiresAt(expire);
        builder.withClaim(key, subject);
        return builder.sign(Algorithm.HMAC256(secret));
    }

    /**
     * 校验Token 如果失败会抛异常
     * 获取Token的Payload
     *
     * @param token
     */
    public DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }


    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
